﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;

namespace Metronome
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        UIElementRenderer elementRenderer;

        private struct TimeSig
        {
            public int top;
            public int bottom;

            public TimeSig(int top, int bottom)
            {
                this.top = top;
                this.bottom = bottom;
            }
        }

        TimeSig[] signatures;
        int currentSig;
        int currentBeats = 90;

        int currentBeat;

        const int minBeats = 20;
        const int maxBeats = 300;

        TimeSpan nextBeat;
        TimeSpan beatLength
        {
            get
            {
                return new TimeSpan(0, 0, 0, 0,
                    60000 / currentBeats);
            }
        }

        SoundEffect sound;
        SpriteFont font;

        Texture2D[] gnome;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            signatures = new TimeSig[9];
            signatures[0] = new TimeSig(2, 2);
            signatures[1] = new TimeSig(3, 2);
            signatures[2] = new TimeSig(2, 4);
            signatures[3] = new TimeSig(3, 4);
            signatures[4] = new TimeSig(4, 4);
            signatures[5] = new TimeSig(8, 4);
            signatures[6] = new TimeSig(3, 8);
            signatures[7] = new TimeSig(7, 8);
            signatures[8] = new TimeSig(8, 8);

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            sound = contentManager.Load<SoundEffect>("c5");
            font = contentManager.Load<SpriteFont>("font");

            gnome = new Texture2D[3];
            gnome[0] = contentManager.Load<Texture2D>("gnome0");
            gnome[1] = contentManager.Load<Texture2D>("gnome1");
            gnome[2] = contentManager.Load<Texture2D>("gnome2");

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        private int currentGnome;

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            foreach (TouchLocation loc in TouchPanel.GetState())
            {
                if (loc.State == TouchLocationState.Moved
                    || loc.State == TouchLocationState.Pressed)
                {
                    float range = Math.Min(Global.ScreenHeight, loc.Position.Y) / (float)Global.ScreenHeight;
                    if (loc.Position.X < 50)
                    {
                        currentSig = (int)(range * signatures.Length);
                    }
                    else if (loc.Position.X > Global.ScreenWidth - 50)
                    {
                        currentBeats = (int)(range * (maxBeats - minBeats)) + minBeats;
                    }
                }
            }

            nextBeat -= e.ElapsedTime;
            if (nextBeat <= TimeSpan.Zero)
            {
                currentBeat++;
                currentGnome = 1 - currentGnome;
                nextBeat += beatLength;

                if (currentBeat > signatures[currentSig].top)
                {
                    currentBeat = 1;
                    sound.Play(1, 1, 0);
                }
                else
                    sound.Play();
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();

            Texture2D usetex = gnome[currentGnome * 2];
            if (nextBeat <= new TimeSpan(0, 0, 0, 0, (int)(beatLength.TotalMilliseconds / 2f))) usetex = gnome[1];
            spriteBatch.Draw(
                usetex,
                Vector2.Zero,
                Color.White);

            spriteBatch.DrawString(
                font,
                signatures[currentSig].top + "/" + signatures[currentSig].bottom,
                new Vector2(60, 10),
                Color.White);
            spriteBatch.DrawString(
                font,
                currentBeats.ToString(),
                new Vector2(Global.ScreenWidth - 60 - font.MeasureString(currentBeats.ToString()).X, 10),
                Color.White);

            int barwidth = 10;
            int sliderwidth = 20;
            int zonewidth = 50;

            spriteBatch.Draw(
                Global.white,
                new Rectangle(zonewidth / 2 - barwidth / 2, 3, barwidth, Global.ScreenHeight - 6),
                Color.Gray);
            spriteBatch.Draw(
                Global.white,
                new Rectangle(Global.ScreenWidth - (zonewidth / 2 - barwidth / 2), 3, barwidth, Global.ScreenHeight - 6),
                Color.Gray);

            spriteBatch.Draw(
                Global.white,
                new Rectangle(zonewidth / 2 - sliderwidth / 2, (int)(Global.ScreenHeight * currentSig / (float)signatures.Length), sliderwidth, 10),
                Color.White);
            spriteBatch.Draw(
                Global.white,
                new Rectangle(Global.ScreenWidth - (zonewidth / 2 - sliderwidth / 2) - sliderwidth / 2, (int)(Global.ScreenHeight * (currentBeats - minBeats) / (float)maxBeats), sliderwidth, 10),
                Color.White);

            elementRenderer.Render();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

            spriteBatch.End();
        }
    }
}